/**
 * Imported packages
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @authors BENSON WACHIRA, DOROTHY SARPONG, STANLEY ANKU
 * MICHAEL ESHUN & MAKAFUI AMEZAH
 */

/**
 * 
 * Controller for the exporting data in database
 */
public class ControllerExport {
   
    /**
     * variable and object declarations
     */
    PrintWriter outPutStream=null;
    String path="";
    File file=null;
    Connection conn=null;
    String querry;
    Statement st=null;

    
    /**
     * Default constructor
     */
    public void ControllerExport(){
    }
    
    /**
     * Method to get destination for the data to be exported 
     */
    private void getSaveLocation() {
   // parent component of the dialog
    JFrame parentFrame = new JFrame();
 
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Specify a file to save");   
 
     int userSelection = fileChooser.showSaveDialog(parentFrame);
 
    if (userSelection == JFileChooser.APPROVE_OPTION) {
    File fileToSave = fileChooser.getSelectedFile();
    path=fileToSave.getAbsolutePath();
    System.out.println("Save as file: " + fileToSave.getAbsolutePath());
    }
    file = new File(path);
    }
  
    /**
     * Method to list available orders
     */
    public void listOrders(){
    try{
        
        Class.forName("com.mysql.jdbc.Driver");
        conn =(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/jetwingdb?zeroDateTimeBehavior=convertToNull","root","");
        querry="SELECT * FROM Orders ;" ;
        st=conn.prepareStatement(querry);
        st.execute("USE jetwingdb;");

        try{
            getSaveLocation();
            outPutStream=new PrintWriter(new FileOutputStream(path, true));

        }
        catch(FileNotFoundException  e){
            JOptionPane.showMessageDialog(null,e.toString());
        }
        ResultSet rs= st.executeQuery(querry);
   while(rs.next()){ 
   outPutStream.println( rs.getString("Name")+"  "+ rs.getString("passPortNo")+"  "+rs.getString("email")+"  "+rs.getString("phoneNO")
           +" " +rs.getString("flightNo")+"  "+rs.getString("seatNo")+"  "+rs.getString("fFrom")+"  "+rs.getString("destination")
                   +"  "+rs.getString("depatureTime")+" "+ rs.getString("arrivalTime"));
   
   }
   JOptionPane.showMessageDialog(null,"Saving Completed");
        
    outPutStream.close();
   st.close();
   conn.close();
  
    }  
    catch(Exception e){
    JOptionPane.showMessageDialog(null,e);
    }
    
    }
}